// server.js
const express = require('express')
const session = require('express-session')
const bodyParser = require('body-parser')
const cors = require('cors')

const app = express()

const user = ''
app.use(bodyParser.json())
app.use(cors({ origin: 'http://localhost:5173', credentials: true })) // 允许来自 http://localhost:8080 的请求，并允许凭证
// app.use(cors({}))
app.use(
  session({
    secret: 'your_secret_key',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false, httpOnly: true, maxAge: 24 * 60 * 60 * 1000 }, // 设置 cookie 有效期为 24 小时
  })
)

app.post('/login', (req, res) => {
  const { username, password } = req.body
  // 假设这里进行了用户名和密码的验证
  if (username === 'admin' && password === '123') {
    user = req.session.user = { id: 1, username: 'admin' }
    res.json({
      success: true,
      message: 'Logged in successfully',
      user: req.session.user,
    })
  } else {
    res.status(401).json({
      success: false,
      message: 'Invalid credentials',
    })
  }
})

// app.post('/login', (req, res) => {
//   try {
//     const { username, password } = req.body
//     // 假设这里进行了用户名和密码的验证
//     if (username === 'admin' && password === 'password') {
//       user = req.session.user = { id: 1, username: 'admin' }
//       res.json({
//         success: true,
//         message: 'Logged in successfully',
//         user: req.session.user,
//       })
//     } else {
//       res.status(401).json({ success: false, message: 'Invalid credentials' })
//     }
//   } catch (err) {
//     console.error('Error during login:', err)
//     res.status(500).json({ success: false, message: 'Internal Server Error' })
//   }
// })

app.get('/profile', (req, res) => {
  if (user) {
    res.json({ user })
  } else {
    res.status(401).json({ message: 'Please log in' })
  }
})

app.listen(3000, () => {
  console.log('Session_Server is running on port 3000')
})
